import Vue from "vue";
import Vuex from "vuex";
import { getMenuList } from "@/api";
//引入  allRoutes
import allRoutes from "../router/allRoutes";
//引入递归函数
import recursionRoutes from "../utils/recursionRoutes";
//引入动态路由
import dynamicRoutes from "../router/dynamicRoutes";
//引入router
import router from "../router";
Vue.use(Vuex);
let permissionButtons = JSON.parse(localStorage.getItem('Lorenzo-permission-buttons')) || {};
export default new Vuex.Store({
  state: {
    //vuex里面的内容  在当前页面刷新之后，会执行这里  然后数据会丢失，
    //我们应该怎么做呢，  存一份到本地存储就行了

    //  我们使用  短路运算 JSON.parse(localStorage.getItem("Lorenzo-userInfo")) || ""
    //  刷新页面 会丢失用户信息，所以要从localstroage里面获取

    userInfo: JSON.parse(localStorage.getItem("Lorenzo-userInfo")) || "{}",
    menuList: [], //定义用户侧边栏的菜单
    permissionButtons,
    crumbs: [] // 存放面包屑的
  },
  mutations: {
    //更改userInfo
    SET_USERINFO(state, payload) {
      state.userInfo = payload;
    },
    SET_MENULIST(state, payload) {
      state.menuList = payload;
      console.log(state.menuList);
      //动态的路由  添加到routes中
      // 核心的方法   动态方法
      //   router.addRoutes(符合路由配置规则的数据)
      //添加之前  做一件事
      //1、将menuList  赋值给dynamicRoutes
      let target = dynamicRoutes.find(item => item.path === "/");
      target.children = [...state.menuList];
      console.log(dynamicRoutes);
      //2、动态添加路由配置到  router/主路由中
      router.addRoutes(dynamicRoutes);
    },
    SET_CRUMBS(state, payload) {
      state.crumbs = payload;
    },
    SET_PERMISSION_BUTTONS(state, payload) {
      state.permissionButtons = payload
    },
  },
  actions: {
    //发送请求，获取用户的菜单的数据
    async FETCH_MENULIST({ commit }) {
      //结构思路

      let userMenu = await getMenuList();
      console.log(userMenu);
      // 通过allRoutes 和请求 回来的用户菜单数据进行对比，将结果提交给mutaitons

      let sideMenu = recursionRoutes(allRoutes, userMenu.data.menuList);
      console.log(sideMenu);
      // console.log(sideMenu)
      commit("SET_MENULIST", sideMenu);
      // 将结果   提交过  mutations
      //需要引入  递归的方法和  allRoutes
      // getMenuList()
      //   .then(res => {
      //     console.log(res);
      //   })
    }
  },
  modules: {}
});
